<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2017/1/13
 * Time: 16:04
 */

namespace YMApi\Repositories;


use YMApi\Model\CategoryModel;
use YMApi\Model\TouchCategoryModel;

/**
 * Class CategoryRepository
 * @package SDXApi\Repositories
 */
class CategoryRepository
{
	/**
	 * @var CategoryModel
	 */
	protected $categoryModel;

	/**
	 * @var TouchCategoryModel
	 */
	protected $touchCategoryModel;

	/**
	 * CategoryRepository constructor.
	 */
	public function __construct()
	{
		$this->categoryModel = new CategoryModel();
		$this->touchCategoryModel = new TouchCategoryModel();
	}

	/**
	 * Created by Jerry
	 * @return array|bool
	 */
	public function getCategoryParentList()
	{
		$data = $this->findCategory();

		$category = self::categoryForLevel($data);
		return $category;
	}


	/**
	 * 获取指定分类下所有子分类
	 * Created by Jerry
	 * @param $id
	 * @return array|bool
	 */
	public function checkCategoryById($id)
	{
		if (empty($id)) {
			return false;
		}

		$data = $this->getCategoryById($id);

		if (empty($data)) {
			return false;
		}

		$categories = self::categoryForLevel($data, 'child', $id);

		return $categories;
	}

	protected function getCategoryById($id)
	{
		if (empty($id)) {
			return false;
		}

		return $this->categoryModel->findCategoryByCatId($id);
	}

	/**
	 * Created by Jerry
	 * @return mixed
	 */
	protected function findCategory()
	{
		return $this->categoryModel->findCategoryList();
	}

	/**
	 * Created by Jerry
	 * @param $data
	 * @param string $name
	 * @param int $parentId
	 * @param int $level
	 * @return array|bool
	 */
	static protected function categoryForLevel($data, $name = 'child', $parentId = 0, $level = 0)
	{
		if (empty($data)) {
			return false;
		}

		$arr = array();
		$level += 1;
		foreach ($data as $key => $value) {
			if ($value['parent_id'] == $parentId) {
				if ($level > 3) {
					continue;
				}

				$value['level'] = $level;

				if ($level != 3) {
					unset($value['cat_image']);
				}

				$value[$name] = self::categoryForLevel($data, $name, $value['cat_id'], $level);
				$arr[] = $value;
			}
		}
		return $arr;
	}


	/**
	 * Created by Jerry
	 * @param $categoryId
	 * @return bool|mixed
	 */
	public function findCategoryImage($categoryId)
	{
		if (empty($categoryId)) {
			return false;
		}

		return $this->touchCategoryModel->findImageByCategoryId($categoryId);
	}


}